﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StudyDrag
{
    public partial class frmDragListView : Form
    {
        public frmDragListView()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初始化属性
        /// </summary>
        void Init()
        {
            this.lbDep.AllowDrop = true;
            this.tvDep.AllowDrop = true;
        }

        /// <summary>
        /// 加载一些数据
        /// </summary>
        void LoadData()
        {
            for (int i = 1; i <= 10; i++)
            {
                string itemValue = "有关部门" + i.ToString();
                this.lbDep.Items.Add(itemValue);
            }
        }

        void RegisterEvent()
        {
            this.tvDep.DragDrop += TvDep_DragDrop;
            this.tvDep.DragEnter += TvDep_DragEnter;
        }

        /// <summary>
        /// 当拖拽进入到该区域的时候出发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TvDep_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        /// <summary>
        /// 当完成退拽时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TvDep_DragDrop(object sender, DragEventArgs e)
        {
            string item = (string)e.Data.GetData(DataFormats.Text);
            this.tvDep.Nodes.Add(item);
        }

        /// <summary>
        /// 窗体初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDragListView_Load(object sender, EventArgs e)
        {
            Init();
            LoadData();
            RegisterEvent();
        }

        /// <summary>
        /// 鼠标点击的的时候开始执行拖拽操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbDep_MouseDown(object sender, MouseEventArgs e)
        {
            if (lbDep.SelectedItem == null)
            {
                return;
            }

            lbDep.DoDragDrop(lbDep.SelectedItem, DragDropEffects.Copy);
        }
    }
}
